package com.js.nickcar.module.addcar.baseinfo;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.DatePicker;

import com.js.nickcar.R;
import com.js.nickcar.api.OptionConfig;
import com.js.nickcar.api.UrlConfig;
import com.js.nickcar.api.UrlUtils;
import com.js.nickcar.base.BaseFragment;
import com.js.nickcar.dialog.DialogHelper;
import com.js.nickcar.dialog.EditDialog;
import com.js.nickcar.dialog.OptionDialog;
import com.js.nickcar.dialog.RegionDialog;
import com.js.nickcar.entity.local.BaseCarInfoEntity;
import com.js.nickcar.entity.local.City;
import com.js.nickcar.entity.local.Province;
import com.js.nickcar.entity.remote.CarModelBean;
import com.js.nickcar.entity.remote.OptionBean;
import com.js.nickcar.module.addcar.brand.CarBrandFragment;
import com.js.nickcar.module.addcar.check.CheckCarFragment;
import com.js.nickcar.module.addcar.model.CarModelFragment;
import com.zyzd.commontools.string.DateUtil;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import butterknife.Bind;

import static android.text.InputType.TYPE_CLASS_PHONE;

/**
 * Created by LZY on 2017/9/28.
 */

public class BaseCarInfoFragment extends BaseFragment<BaseCarInfoPresenter>
        implements BaseCarInfoView, BaseCarInfoAdapter.OnItemClickListener,
        OptionConfig, BaseCarInfoEntity.Param, BaseCarInfoEntity.ItemType {

    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;
    public static final int REQUEST_CODE_CAR_MODEL = 301;
    public static final int REQUEST_CODE_ADD_CAR = 302;
    public BaseCarInfoAdapter mAdapter;
    public RegionDialog mRegionDialog;


    private String[] optionKeys = {
            CAR_INFO_SUNROOF,
            CAR_INFO_USAGE,
            CAR_INFO_TRANS_TIMES
    };

    @Override
    public int getLayoutId() {
        return R.layout.fragment_base_car_info;
    }

    @Override
    protected BaseCarInfoPresenter createPresenter() {
        return new BaseCarInfoPresenter();
    }

    public static BaseCarInfoFragment getInstance() {
        return new BaseCarInfoFragment();
    }

    @Override
    protected void initData() {
        mPresenter.getOptions(optionKeys);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext().getApplicationContext()));
        mAdapter = new BaseCarInfoAdapter(getContext(), mPresenter.getData());
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    protected String getTitle() {
        return getString(R.string.base_car_info);
    }

    @Override
    public void onNorItemClick(BaseCarInfoEntity entity, int position) {
        switch (entity.getParam()) {
            case RECEIVE_CITY://地区
                openRegionDialog(entity, position);
                break;
            case CAR_TYPE://车型
                selectCarType(entity, position);
                break;
            case COLOR://车辆颜色
                openEditDialog(entity, position, getString(R.string.please_input_car_color), InputType.TYPE_CLASS_TEXT);
                break;
            case SUNROOF://天窗
                openOptionDialog(entity, position);
                break;
            case SEATS://座位
                openEditDialog(entity, position, getString(R.string.please_input_seat_num), InputType.TYPE_CLASS_NUMBER);
                break;
            case DISPLACEMENT://排量
                openEditDialog(entity, position, getString(R.string.please_input_displacement), InputType.TYPE_CLASS_TEXT);
                break;
            case MILEAGE://行驶里程（万公里）
                openEditDialog(entity, position, getString(R.string.please_input_mileage), InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                break;
            case PLATE_TIME://首次上牌时间
                openDateDialog(entity, position);
                break;
            case SERVICE://使用年限
                openEditDialog(entity, position, getString(R.string.please_input_service), InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                break;
            case USAGE:
                OpenUsageDialog(entity, position);
                break;
            case ENGINE_NO://发动机号
                openEditDialog(entity, position, getString(R.string.please_input_engine_no), InputType.TYPE_CLASS_TEXT);
                break;
            case TRANS_TIMES:
                OpenTransTimesDialog(entity, position);
                break;
        }
    }


    private void openEditDialog(final BaseCarInfoEntity entity, final int position, String hint, int intputType) {
        DialogHelper.openEditDialog(getContext(), entity.getTitle(), entity.getContent(), hint, intputType, new EditDialog.OnConfirmListener() {
            @Override
            public void onConfirm(String content) {
                entity.setContent(content);
                entity.setValue(content);
                mAdapter.notifyItemChanged(position);
            }
        });
    }

    private void openDateDialog(final BaseCarInfoEntity entity, final int position) {
        DialogHelper.openDatePickerDialog(getContext(), mPresenter.getOptionDate(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(year, month, dayOfMonth);
                mPresenter.setOptionDate(calendar.getTime());
                String timeStr = String.format(getString(R.string.base_car_info_date), year, month + 1);
                entity.setContent(timeStr);
                entity.setValue(calendar.getTime().getTime() + "");
                mAdapter.notifyItemChanged(position);
            }
        });
    }

    /**
     * 天窗
     *
     * @param entity
     * @param position
     */
    private void openOptionDialog(final BaseCarInfoEntity entity, final int position) {
        DialogHelper.openOptionDialog(getContext(), mPresenter.getSunroofData(), mPresenter.getOptionSunroof(), new OptionDialog.OnConfirmListener() {
            @Override
            public void onConfirm(OptionBean option) {
                mPresenter.setOptionSunroof(option);
                entity.setContent(option.getValue());
                entity.setValue(option.getKvp_id());
                mAdapter.notifyItemChanged(position);
            }
        });
    }

    /**
     * 使用性质
     */
    public void OpenUsageDialog(final BaseCarInfoEntity entity, final int position) {
        DialogHelper.openOptionDialog(getContext(), mPresenter.getUsageData(), mPresenter.getOptionUsage(), new OptionDialog.OnConfirmListener() {
            @Override
            public void onConfirm(OptionBean option) {
                mPresenter.setOptionUsage(option);
                entity.setContent(option.getValue());
                entity.setValue(option.getKvp_id());
                mAdapter.notifyItemChanged(position);
            }
        });
    }

    /**
     * 过户次数
     */
    public void OpenTransTimesDialog(final BaseCarInfoEntity entity, final int position) {
        DialogHelper.openOptionDialog(getContext(), mPresenter.getTransTimesData(), mPresenter.getOptionTransTimes(), new OptionDialog.OnConfirmListener() {
            @Override
            public void onConfirm(OptionBean option) {
                mPresenter.setOptionTransTimes(option);
                entity.setContent(option.getValue());
                entity.setValue(option.getKvp_id());
                mAdapter.notifyItemChanged(position);
            }
        });
    }


    private void selectCarType(BaseCarInfoEntity entity, int position) {
        Fragment fragment = CarBrandFragment.getInstance();
        fragment.setTargetFragment(this, REQUEST_CODE_CAR_MODEL);
        addFragment(fragment);
    }

    private void openRegionDialog(final BaseCarInfoEntity entity, final int position) {
        String content = entity.getContent();
        String[] arr = null;
        if (!TextUtils.isEmpty(content)) {
            arr = content.split(" ");
        }
        mRegionDialog = DialogHelper.openRegionDialog(getActivity(), new RegionDialog.OnRegionListener() {

            @Override
            public void onPositive(View view, Province province, City city) {
                entity.setContent(province.getName() + " " + city.getName());
                entity.setValue(province.getId() + "|" + province.getName() + "|" + city.getId() + "|" + city.getName());
                mAdapter.notifyItemChanged(position);
            }
        }, arr);
    }

    @Override
    public void onNext(List<BaseCarInfoEntity> lists) {
        for (BaseCarInfoEntity item : lists) {
            if (NEXT.equals(item.getParam())) continue;
            if (TextUtils.isEmpty(item.getContent())) {
                String msg = String.format(getString(R.string.base_car_info_msg),
                        getString(item.getType() == TYPE_SELECT
                                ? R.string.please_select : R.string.please_input),
                        item.getTitle());
                showToast(msg);
                return;
            }
        }

        //下一步提交车辆基本信息
        commitCarBaseInfo(lists);

    }

    @Override
    public void commitCarBaseInfoSuccess(String carId) {
        CheckCarFragment checkCarFragment = CheckCarFragment.getInstance(carId);
        checkCarFragment.setTargetFragment(this, REQUEST_CODE_ADD_CAR);
        addFragment(checkCarFragment);
    }

    private void commitCarBaseInfo(List<BaseCarInfoEntity> lists) {
        Map<String, String> map = UrlUtils.getBaseRequestMap(UrlConfig.API_APPRAISER_CAR);
        for (BaseCarInfoEntity entity : lists) {
            if (NEXT.equals(entity.getParam())) continue;
            if (TextUtils.isEmpty(entity.getContent())) {
                showToast(getString(entity.getType() == TYPE_SELECT
                        ? R.string.please_select : R.string.please_input) + entity.getTitle());
                return;
            }
            map.put(entity.getParam(), entity.getValue());
        }
        mPresenter.commitCarInfo(map);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        if (data != null && requestCode == REQUEST_CODE_CAR_MODEL) {
            CarModelBean carModelBean = data.getParcelableExtra(CarModelFragment.EXTRA_SELECTED_CAR_MODEL);
            List<BaseCarInfoEntity> allData = mAdapter.getAllData();
            for (int i = 0; i < allData.size(); i++) {
                BaseCarInfoEntity entity = allData.get(i);
                if (entity.getParam().equals(BaseCarInfoEntity.Param.CAR_TYPE)) {
                    entity.setContent(carModelBean.getModel_name());
                    entity.setValue(carModelBean.getCar_model_id());
                    mAdapter.notifyItemChanged(i);
                    break;
                }
            }
        } else if (requestCode == REQUEST_CODE_ADD_CAR) {
            //添加成功，关闭该界面
            showToast(getString(R.string.add_car_success));
            finish();
        }
    }
}
